import 'package:lib_bt/BleManager.dart';
import 'package:lib_bt/listener/OnBleConnectListener.dart';
import 'package:lib_bt/listener/OnBleScanListener.dart';

import 'base/LedBleBeanInterface.dart';

///碰一碰连接
class TouchLink implements OnBleScanListener, OnBleConnectListener {
  //单例
  static TouchLink? _instance;

  static TouchLink get instance => _instance ??= TouchLink._();

  TouchLink._() {
    BleManager.instance.addScanListener(this);
    BleManager.instance.addConnectListener(this);
  }


  @override
  void onConnected(String address) {
  }

  @override
  void onDisconnected(String address) {
  }

  @override
  void onMtuChanged(String address, int mtu) {}

  @override
  void onScanResult(result) {
    if (BleManager.instance.isConnecting) {
      return;
    }
    String address = result["address"];
    var bleBean = BleManager.instance.getBleBean<LedBleBeanInterface>(address);
    if (bleBean == null || !bleBean.isAutoConnect) {
      return;
    }
    //信号特别好的设备自动连接
    if (bleBean.rssi > -40) {
      var bleList = BleManager.instance.getConnectBleBeans();
      //跟已经连接的设备类型不一致的不自动连
      if (bleList.isNotEmpty) {
        var lastBle = BleManager.instance.getBleBean<LedBleBeanInterface>(bleList.last.address);
        if (lastBle != null) {
          if (!lastBle.typeIsSame(bleBean)) {
            return;
          }
        }
      }

      BleManager.instance.connect(address);
    }
  }

  @override
  void onStartConnect(String address) {
  }

  @override
  void onStartScan() {}

  @override
  void onStopScan() {}
}
